package com.xiyun.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiyun.admin.entity.Department;
import com.xiyun.admin.mapper.DepartmentMapper;
import com.xiyun.admin.service.DepartmentService;
import com.xiyun.admin.utils.excel.ExcelUtil;
import com.xiyun.admin.utils.excel.data.ExcelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentService departmentService;

    @Override
    public void readExcel(MultipartFile file) throws IOException {
        ExcelUtil.readExcel(file.getInputStream(),departmentService);
    }

    @Override
    public List<ExcelData> downloadExcel() {
        List<ExcelData> finalList = new ArrayList<>(24);
        List<Department> department1 = selectOne();
        List<Department> department2 = selectTwo();

        for (Department departmentOne : department1) {
            ExcelData data = new ExcelData();
            data.setId(departmentOne.getId());
            data.setDeptName(departmentOne.getDeptName());

            List<ExcelData> list = new ArrayList<>();
            for (Department departmentTwo : department2) {
                if (departmentOne.getId().equals(departmentTwo.getPid())){
                    ExcelData data2 = new ExcelData();
                    data2.setId(departmentTwo.getId());
                    data2.setDeptName(departmentTwo.getDeptName());
                    data2.setChildren(null);
                    list.add(data2);
                }
            }
            data.setChildren(list);
            finalList.add(data);
        }
        return finalList;
    }

    //获取一级分类
    private List<Department> selectOne(){
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("pid","0");
        return this.baseMapper.selectList(wrapper);
    }

    //获取二级分类
    private List<Department> selectTwo(){
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.ne("pid","0");
        return this.baseMapper.selectList(wrapper);
    }
}
